package com.fulihui.weixinsdk.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;

/**
 * 
 * Created by LeeSon on 2017/3/30 0030.
 */
public class SslHttpClient implements HttpInvoke {
    private static final Logger        logger = LoggerFactory.getLogger("HTTPCLIENT_UTIL_LOG");

    PoolingHttpClientConnectionManager cm;
    CloseableHttpClient                httpClient;

    public SslHttpClient(int maxTotal, int maxRoute, String certFile, String certPwd) {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(maxTotal);// 最大连接数
        cm.setDefaultMaxPerRoute(maxRoute);// 单路由最大连接数

        if (StringUtils.isBlank(certFile)) {
            throw new IllegalArgumentException("certFile can not be blank");
        }

        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            try (FileInputStream instream = new FileInputStream(new File(certFile))) {
                keyStore.load(instream, certPwd.toCharArray());
            }
            // Trust own CA and all self-signed certs
            SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, certPwd.toCharArray()).build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
                .build();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public String doGet(HttpRequest request) {
        try {
            String fullUrl = HttpUtil.genFullGetUrl(request.getUrl(), request.getParams(), request.getUrlFoot());
            return HttpUtil.executeGet(httpClient, fullUrl);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public String doPost(HttpRequest request) {
        String resp = null;
        try {
            // 如果有请求体，params当作请求参数，否则params当form表单
            if (StringUtils.isBlank(request.getData())) {
                resp = HttpUtil.executePost(httpClient, request.getUrl(), request.getParams());
            } else {
                String fullUrl = HttpUtil.genFullGetUrl(request.getUrl(), request.getParams(), request.getUrlFoot());
                resp = HttpUtil.executePost(httpClient, fullUrl, request.getData());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resp;
    }

    @Override
    public void close() {
        try {
            if (null != httpClient) {
                httpClient.close();
            }
            if (null != cm) {
                cm.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
